package com.topteam.component.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.topteam.frame.controllor.BaseController;
import com.topteam.utility.StringUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 表格控件 Column
 * @author Jiang Feng
 *
 */
public class TopColumn extends TopTemplateModel{
	
	public static final String TAG = "column";
	
	private BaseController controller;
	
	private String name;
	
	private String title;
	
	private Double width;
	
	private String align;
	
	private Boolean sortable =false;
	
	private String formatter;
	
	private int rowspan;
	
	private int colspan;
	
	private Boolean hidden = false;
	
	private Boolean checkbox = false;
	
	private String editor;
	
	public TopColumn(BaseController controller){
		this.controller = controller;
	}
	
	private void initPara(Map para, Environment env) throws TemplateException{
		name = getStrPara("name", para, env);
		title = getStrPara("title", para, env);
		align = getStrPara("align", para, env);
		formatter = getStrPara("formatter", para, env);
		width = getDoublePara("width", para, env);
		sortable = getBoolPara("sortable", para, env,sortable);
		rowspan = getIntPara("rowspan", para, env);
		colspan = getIntPara("colspan", para, env);
		hidden = getBoolPara("hidden", para, env,hidden);
		checkbox = getBoolPara("checkbox", para, env,checkbox);
		
		editor = getStrPara("editor", para, env);
	}

	@Override
	public void execute(Environment env, Map para, TemplateModel[] arg2,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		initPara(para,env);
		Writer w = env.getOut();
		w.write("<th data-options=\"");
		if(width>0)
			w.write("width:"+width+", ");
		if(StringUtil.isNotNull(align))
			w.write("align:'"+align+"', ");
		if(sortable)
			w.write("sortable:'"+sortable.toString()+"', ");
		if(hidden)
			w.write("hidden:"+hidden.toString()+", ");
		if(checkbox)
			w.write("checkbox:"+checkbox.toString()+", ");
		if(StringUtil.isNotNull(formatter))
			w.write("formatter:"+formatter+", ");
		if(StringUtil.isNotNull(editor))
			w.write("editor:"+editor+",");
		w.write("field:'"+name+"' ");
		w.write("\"");
		if(rowspan>0)
			w.write("rowspan=\""+rowspan+"\" ");
		if(colspan>0)
			w.write("colspan=\""+colspan+"\" ");
		w.write(" >");
		w.write(title==null?"":title);
		w.write("</th>");
		//writeScript(w);
		
		cleanPara();
	}
	
	private void cleanPara() {
		checkbox= false;
		name = null;
		title = null;
		align = null;
		formatter= null;
		width = null;
		sortable =false;
		rowspan =0;
		colspan=0;
		hidden= false;
		editor = null;
	}

	public void writeScript(Writer w) throws IOException{
		w.write("<script type=\"text/javascript\">");
		
		w.write("</script>");
	}

	
}
